package com.maduar.mybatis.demo.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.client.AMQP.PROTOCOL.PORT;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @date 2021-04-30 20:39
 */
public class RabbitProducter {

    private static final String EXCHANGE_NAME = "exchange_demo";
    private static final String ROUTING_KEY = "routingkey_demo";
    private static final String QUEUE_NAME = "queue_demo";
    private static final String IP_ADDRESS = "119.45.57.46";
    private static final int PORT = 5672;//RabbitMQ服务端默认端口号为5672

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = null;
        Channel channel = null;
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(IP_ADDRESS);
            factory.setPort(PORT);
            factory.setUsername("root");
            factory.setPassword("root");

            connection = factory.newConnection();//创建连接
            channel = connection.createChannel();//创建信道

            //创建一个 type="direct"、持久化的、非自动删除的交换器 channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null); //创建一个持久化、非排他的、非自动删除的队列 channel.queueDeclare(QUEUE_NAME, true, false, false, null); //将交换器与队列通过路由键绑定
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY); //发送一条持久化的消息:hello world!
            String message = "Hello World!";
            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY,
                    MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes()); //关闭资源
            System.out.println("======success=====");
        } catch (Exception e) {
            e.printStackTrace();
            channel.close();
            connection.close();
        }

        channel.close();
        connection.close();
    }
}
